package cn.car.biz.carAccess.eventListener;

import cn.car.biz.carAccess.event.VehicleChangeEvent;
import cn.car.domains.dto.BaseResponse;
import cn.car.domains.entity.VehicleCommonInfoEntity;
import cn.car.domains.entity.VehicleEntryExitInfoEntity;
import cn.car.domains.enums.UploadGovStatusEnum;
import cn.car.service.VehicleCommonInfoService;
import cn.car.service.VehicleEntryExitInfoService;
import cn.car.service.remote.TjRemoteService;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class CreateEntryExitVehicleUploadGovListener implements ApplicationListener<VehicleChangeEvent> {

    @Override
    public boolean supportsAsyncExecution() {
        return true;
    }

    @Resource
    private VehicleEntryExitInfoService vehicleEntryExitInfoService;

    @Resource
    private VehicleCommonInfoService vehicleCommonInfoService;

    @Resource
    private TjRemoteService tjRemoteService;

    @Override
    public void onApplicationEvent(VehicleChangeEvent event) {
        Long id = event.getId();

        VehicleEntryExitInfoEntity vehicleEntryExitInfoEntity = vehicleEntryExitInfoService.queryById(id);

        VehicleCommonInfoEntity vehicleCommonInfoEntity = vehicleCommonInfoService.getVehicleByAssociationId(id);

        try {
            VehicleEntryExitInfoEntity updateEntity = new VehicleEntryExitInfoEntity();
            updateEntity.setId(vehicleEntryExitInfoEntity.getId());
            BaseResponse baseResponse = tjRemoteService.putRegisterVehicleInfo(vehicleEntryExitInfoEntity, vehicleCommonInfoEntity);
            if (null == baseResponse) {
                log.info("[GOV_TJ putRegisterVehicleInfo] ignore, 未联网 vehicleNumber:{}", vehicleEntryExitInfoEntity.getVehicleNumber());
            } else if ("200".equals(baseResponse.getCode())) {
                log.info("[GOV_TJ putRegisterVehicleInfo] success, 上报车辆备案信息成功, vehicleNumber:{}, baseResponse:{}", vehicleEntryExitInfoEntity.getVehicleNumber(), JSONObject.toJSONString(baseResponse));
                updateEntity.setGovUploadStatus(UploadGovStatusEnum.SUCCESS.name());
            } else {
                log.error("[GOV_TJ putRegisterVehicleInfo] 上报车辆备案信息错误 vehicleNumber:{},baseResponse:{}", vehicleEntryExitInfoEntity.getVehicleNumber(), JSONObject.toJSONString(baseResponse));
                updateEntity.setGovUploadStatus(UploadGovStatusEnum.FAIL.name());
            }
            vehicleEntryExitInfoService.update(updateEntity);
        } catch (Exception e) {
            log.error("[GOV_TJ putRegisterVehicleInfo] error e", e);
        }

    }
}
